import "./index.scss";
import { Upload, Form, Input, message } from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import type { FormProps, UploadFile } from "antd";
import { useEffect, useState } from "react";
import AV from "leancloud-storage";
import { useSelector } from "react-redux";
import { select_userInfo } from "@/store/slice/userInfo";
import { editUserInfo } from "@/util/request";
import { useNavigate } from "react-router-dom";
function PersonInfo() {
	type FieldType = {
		avatar?: string;
		name: string;
		money: string;
		stack: string;
		degree: string;
		time: string;
		wx: string;
	};
	type initUserInfo = {
		name: string;
		money: string;
		stack: string;
		degree: string;
		time: string;
		wx: string;
	};
	const [loading, setLoading] = useState(false);
	const [imageUrl, setImageUrl] = useState<string>("");
	const [fileList, setFileList] = useState<UploadFile[]>();
	const userInfo = useSelector(select_userInfo);
	const navigate = useNavigate();
	const [form] = Form.useForm();
	const isEdit = userInfo?.has_person_info;
	const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
		console.log("Success:", values);
	};
	useEffect(() => {
		if (isEdit) {
			setImageUrl(userInfo.avatar);
			setFileList([
				{
					url: userInfo.avatar,
					uid: userInfo.avatar,
					name: userInfo.avatar,
				},
			]);
			let time = formattedDate(userInfo.created);
			form.setFieldsValue({
				name: userInfo.name,
				money: userInfo.money,
				stack: "vue",
				degree: "大专",
				time,
				wx: userInfo.vChat,
			});
		}
	}, [isEdit]);
	function formattedDate(isoDateString: Date) {
		const date = new Date(isoDateString);
		const year = date.getUTCFullYear(); // 获取年份
		const month = date.getUTCMonth() + 1; // 获取月份，注意月份是从0开始的
		const day = date.getUTCDate(); // 获取日期
		const formattedMonth = month.toString().padStart(2, "0"); // 确保月份是两位数
		const formattedDay = day.toString().padStart(2, "0"); // 确保日期是两位数
		return `${year}-${formattedMonth}-${formattedDay}`;
	}
	const uploadButton = (
		<button style={{ border: 0, background: "none" }} type="button">
			{loading ? <LoadingOutlined /> : <PlusOutlined />}
			<div style={{ marginTop: 8 }}>上传头像</div>
		</button>
	);
	const onChange = (info: any) => {
		if (info.fileList.length) {
			const file = new AV.File("avatar.jpg", info.file);
			file.save().then(
				(file: any) => {
					console.log(`文件保存完成。URL`, file.url());
					setImageUrl(file.url());
				},
				(error) => {
					console.log(error, "error");
				}
			);
		}
	};
	const beforeUpload = (file: UploadFile) => {
		return false;
	};
	const onRemove = (file: UploadFile) => {
		setImageUrl("");
	};

	const handleBack = () => {
		navigate(-1);
	};
	const handleEdit = () => {
		form
			.validateFields()
			.then(async (data: initUserInfo) => {
				let res = await editUserInfo(
					{
						name: data.name,
						vChat: data.wx,
						avatar: imageUrl,
						graduation_time: data.time,
						money: Number(data.money),
					},
					userInfo._id
				);
				if (res.code !== -1) {
					message.success("修改成功");
					if (userInfo.role === "student") {
						navigate("/exam_select");
					}
				}
			})
			.catch((err) => {
				console.log(err);
			});
	};
	return (
		<div className="personInfo_wrap">
			<div className="personInfo_title">
				{isEdit ? "修改" : "完善"}
				<span>个人信息</span>
			</div>
			<div className="personInfo_form">
				<Form
					name="basic"
					labelCol={{ span: 4 }}
					wrapperCol={{ span: 20 }}
					style={{ maxWidth: 450 }}
					onFinish={onFinish}
					labelAlign="left"
					form={form}
				>
					<Form.Item<FieldType> label="头像">
						<Upload
							listType="picture-card"
							className="avatar-uploader"
							maxCount={1}
							onChange={onChange}
							beforeUpload={beforeUpload}
							onRemove={onRemove}
							fileList={fileList}
						>
							{imageUrl ? null : uploadButton}
						</Upload>
					</Form.Item>

					<Form.Item<FieldType>
						label="花名"
						name="name"
						rules={[{ required: true, message: "请输入花名!" }]}
					>
						<Input />
					</Form.Item>

					<Form.Item<FieldType>
						label="当前薪资"
						name="money"
						rules={[{ required: true, message: "请输入当前薪资!" }]}
					>
						<Input />
					</Form.Item>

					<Form.Item<FieldType>
						label="技术栈"
						name="stack"
						rules={[{ required: true, message: "请输入技术栈!" }]}
					>
						<Input />
					</Form.Item>

					<Form.Item<FieldType>
						label="学历"
						name="degree"
						rules={[{ required: true, message: "请输入学历!" }]}
					>
						<Input />
					</Form.Item>
					<Form.Item<FieldType>
						label="毕业时间"
						name="time"
						rules={[{ required: true, message: "请输入毕业时间!" }]}
					>
						<Input />
					</Form.Item>
					<Form.Item<FieldType>
						label="微信号"
						name="wx"
						rules={[{ required: true, message: "请输入微信号!" }]}
					>
						<Input />
					</Form.Item>
					<div className="btn">
						<div className="btn_sure" onClick={handleEdit}>
							确认修改
						</div>
						{isEdit ? (
							<div className="btn_back" onClick={handleBack}>
								返回考试
							</div>
						) : null}
					</div>
				</Form>
			</div>
		</div>
	);
}

export default PersonInfo;
